﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Thread生命周期
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Thread _thread;
        private int _index;
        private void button1_Click(object sender, EventArgs e)
        {
            _thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(600);
                        textBox1.Invoke(new Action(() =>
                        {
                            textBox1.AppendText($"{_index++},");
                        }));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "," + _index);
                    }

                }
            });
            _thread.Start();
        }
        /// <summary>
        /// 挂起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (_thread != null && (_thread.ThreadState == ThreadState.Running || _thread.ThreadState == ThreadState.WaitSleepJoin))
            {
                _thread.Suspend();
            }
        }
        /// <summary>
        /// 恢复已挂起的线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (_thread != null && (_thread.ThreadState == ThreadState.Suspended))
            {
                _thread.Resume();
            }

        }
        /// <summary>
        ///  中断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            _thread.Interrupt();
        }
        /// <summary>
        /// 销毁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            _thread.Abort();
        }
    }
}
